package utilmyio;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import javax.swing.JOptionPane;

import Myjavaben.Employee;

public class MyIOper {
	public ArrayList<Employee> getFileData(String filename) {
		FileInputStream fis;
		ArrayList<Employee> arlist=new ArrayList<Employee>();
		try {
			fis = new FileInputStream(filename);
			InputStreamReader isr=new InputStreamReader(fis,"UTF-8");
			BufferedReader bw=new BufferedReader(isr);
			String line=null;
			while((line=bw.readLine())!= null) {
				String[] fid=line.split("\\s+");
				Employee e=new Employee();
				e.setName(fid[0]);
				e.setDept(fid[1]);
				e.setPhone(fid[2]);
				arlist.add(e);
				
			}
		} catch (FileNotFoundException | UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return arlist;
		
	}//end of method
	
	public void setFileData(String filename,ArrayList<Employee> result) {
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(filename);
			OutputStreamWriter isr=new OutputStreamWriter(fos,"UTF-8");
			BufferedWriter bw=new BufferedWriter(isr);
			for(Employee m:result) {
				bw.write(m.toString()+"\n");
				//bw.newLine();
			}
			bw.flush();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(null, "File lost");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(null, "Charset not support");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(null, "Not output result");
		}
		
	}

}
